#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import datetime
from django.utils import simplejson
import cgi

from model import Question
from model import Lecture

class MyHandler(webapp.RequestHandler):
    
    # Receives course or question, returns an array with the questions
    def get(self):
        form = cgi.FieldStorage()
        if form.getvalue("lectureKey") != None:
            questions = db.Query(Question).filter("lecture =", Lecture.get(form.getvalue("lectureKey")))
        else:
            questions = Question.get([form.getvalue("questionKey")])

        questionsObj = []

        for q in questions:
            answersArr = []
            for a in q.answers:
                answersArr.append({ "text": a})
            obj = { "name":q.name, "text": q.text, "answers":answersArr, "key": str(q.key())}
            questionsObj.append(obj)

        self.response.out.write(simplejson.dumps(questionsObj))
                            
def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()